import React from "react";
import Admin from "../../layout/Admin";
import QuotationModel from "../../model/quotation";
import {Table, Image, Popover, Modal, Form, Button, Input, InputNumber, Upload, Switch} from "antd";
import PaginationFooter from "../../component/PaginationFooter/PaginationFooter";
import moment from "moment";
import { UploadOutlined, InboxOutlined, CloseCircleOutlined, } from '@ant-design/icons';
import Info from "../../service/info";


export const log = console.log.bind(console)

export const formLayout = {
    labelCol: { span: 8 },
    wrapperCol: { span: 16 },
}
export const formTailLayout = {
    wrapperCol: { offset: 8, span: 16 },
}

export function getBase64(file) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = error => reject(error);
    });
}

const {
    Search,
} = Input


class Quotation extends React.Component {

    constructor(props) {
        super(props)
        this.model = new QuotationModel()
        this.columns = [
            // Id: 178
            {
                dataIndex: 'Id',
                title: 'Id',
            },
            // Pinpai: "雨林"
            {
                dataIndex: 'Pinpai',
                title: '品牌',
            },
            // Name: "雨林2021年紫电清霜"
            {
                dataIndex: 'Name',
                title: '品名',
            },
            // Price: 4750000
            {
                dataIndex: 'Price',
                title: '价格',
            },
            // Gongyi: "生茶"
            {
                dataIndex: 'Gongyi',
                title: '工艺'
            },
            // Style: "饼茶"
            {
                dataIndex: 'Style',
                title: '类型'
            },
            // Guige: "357克/片5片/提2提/件"
            {
                dataIndex: 'Guige',
                title: '规格'
            },
            // Pici: ""
            {
                dataIndex: 'Pici',
                title: '批次'
            },
            // Weight: 3600
            {
                dataIndex: 'Weight',
                title: '重量',
                render: weight => <span>{weight / 100}千克</span>
            },
            // Unit: ""
            // {
            //     dataIndex: 'Unit',
            //     title: 'Unit'
            // },
            // Up: -2061
            {
                dataIndex: 'Up',
                title: '涨幅'
            },

            // Xulie: ""
            {
                dataIndex: 'Xulie',
                title: '序列'
            },
            // Hot: 0
            {
                dataIndex: 'Hot',
                title: '热度'
            },
            // Createtime: 1618552171
            // Productiondate: 1609430400
            {
                dataIndex: 'Productiondate',
                title: '生产日期',
                render: (time) => moment(new Date(time * 1000)).format('YYYY')
            },
            // Expiredate: 0
            {
                dataIndex: 'Expiredate',
                title: '过期日期',
                render: (time) => time > 0 && moment(new Date(time * 1000)).format('YYYY-MM-DD HH:mm')
            },
            // Detailimgs: null
            {
                dataIndex: 'Imgs',
                title: '轮播图',
                render: (imgs) => {
                    return <Popover
                        title='轮播图'
                        trigger='click'
                        content={<div>
                            {imgs && imgs.map((img, index) => <img src={img} key={index} alt='' style={{width: 200,}}/>)}
                        </div>}
                    >
                        <a>查看</a>
                    </Popover>
                }
            },
            {
                dataIndex: 'Detailimgs',
                title: '详情图',
                render: (imgs, record) => {
                    // log(imgs)
                    if (imgs && imgs.length > 0) {
                        return <Popover
                            title='轮播图'
                            trigger='click'
                            content={<div>
                                {imgs && imgs.map((img, index) => <img src={img} key={index} alt='' style={{width: 200,}}/>)}
                            </div>}
                        >
                            <a>查看</a>
                        </Popover>
                    } else {
                        return <a onClick={() => this.callEdit(record)}>添加</a>
                    }
                }
            },

            {
                title: '操作',
                render: (recode) => {
                    return <div className='action-links'>
                        <a
                            onClick={() => this.callEdit(recode)}
                        >编辑</a>
                    </div>
                }
            },

            // Imgs: (2) ["https://file.youfuchaye.com/project/files/Youfucha…20/Thumbnail/1fe9d9fc5ffe4c04ac5daabf193b0132.jpg", "https://file.youfuchaye.com/project/files/Youfucha…20/Thumbnail/33a10a5a104345ee9e21a06ea37950eb.jpg"]

            // Priceupdatetime: 1616860800

        ]
        this.state = {
            list: [],
            p: 0,
            modal: {
                add: false,
                preview: false,
            },
            previewImage: null,
            previewTitle: '',
            edit: false,
            editValue: null,
            imgs: [],
            detailImgs: [],

            brand: '',
            technology: '',
            year: 0,
            hot: 0,
            up: 0,
            price: 0,

            quotation: null,
        }
    }

    componentDidMount() {
        this.all()
    }

    all = () => {
        const params = {
            PinPai: [],   //为空则不过滤品牌
            Gongyi: [], //为空则不过滤工艺
            Year: [], //0不过滤
            P: this.state.p, //页数，从0开始
            Hot: this.state.hot, //0不过滤，1从高到低，2从低到高
            Price: this.state.price, //0不过滤，1从高到低，2从低到高
            Up: this.state.up, //0不过滤，1从高到低，2从低到高
        }
        if (this.state.brand.length > 0) {
            params.PinPai = [this.state.brand]
        }
        if (this.state.year > 0) {
            params.Year = [this.state.year]
        }
        if (this.state.technology.length > 0) {
            params.Gongyi = [this.state.technology]
        }
        this.model
            .all(params)
            .then(res => {
                const code = res.data.code
                if (code === 0) {
                    const data = res.data.data
                    log('all,', data)
                    this.setState({
                        list: data,
                    })
                }
            })
    }

    onAdd = (value) => {
        value.Imgs = this.state.imgs
        value.Detailimgs = this.state.detailImgs
        if (this.state.edit) {
            value = {
                ...this.state.editValue,
                ...value,
            }
            const imgs = this.state.editValue.Imgs
            const detailImgs = this.state.editValue.Detailimgs
            if (imgs) {
                value.Imgs = [...this.state.editValue.Imgs, ...this.state.imgs,]
            }
            if (detailImgs) {
                if (this.state.editValue.Detailimgs) {
                    value.Detailimgs = [...this.state.editValue.Detailimgs, ...this.state.detailImgs,]
                } else {
                    value.Detailimgs = [...this.state.detailImgs,]
                }
            }
        }
        this.model.add(value)
            .then(res => {
                if (res.data.code === 0) {
                    Info.success('上传/编辑成功')
                    this.addForm.resetFields()
                    this.cancelModal('add')
                    this.setState({
                        imgs: [],
                        detailImgs: [],
                        edit: false,
                    })

                    this.all()
                } else {
                    Info.warning('失败')
                }
            })
    }

    onYearSearch = (year) => {
        this.setState({
            p: 0,
            year: parseInt(year),
        }, () => this.all())
    }

    onTechnologySearch = (value) => {
        this.setState({
            p: 0,
            technology: value,
        }, () => this.all())
    }

    onBrandSearch = (value) => {
        this.setState({
            p: 0,
            brand: value,
        }, () => this.all())
    }

    onNameSearch = (value) => {
        log(value)
        this.setState({
            p: 0,
            brand: '',
        }, () => this.findByName(value))
    }

    findByName = (name) => {
        if (name === '') {
            this.all()
        } else {
            const params = {
                Keys: [name,],
                P: this.state.p,
            }
            this.model
                .findByName(params)
                .then((res) => {
                    const code = res.data.code
                    if (code === 0) {
                        const data = res.data.data.d
                        this.setState({
                            list: data,
                        })
                    }
                })
        }
    }



    onInputChange = (value, name) => {
        this.setState({
            [name]: value,
        })
    }

    onSortChange = (value, name, param) => {
        if (value) {
            this.setState({
                [name]: param,
                p: 0,
            }, () => this.all())
        } else {
            this.setState({
                [name]: 0,
                p: 0,
            }, () => this.all())
        }
    }

    callEdit = (record) => {
        this.callModal('add')
        this.setState({
            editValue: record,
            edit: true,
        })

        setTimeout(() => {
            this.addForm.setFieldsValue({
                ...record,
            })
        }, 0)
    }

    prevPage = () => {
        this.setState({
            p: this.state.p - 1,
        }, () => this.all())
    }

    nextPage = () => {
        this.setState({
            p: this.state.p + 1,
        }, () => this.all())
    }

    callModal(key) {
        this.setState({
            ...this.state,
            modal: {
                ...this.state.modal,
                [key]: true,
            }
        })
    }

    cancelModal(key) {
        this.setState({
            ...this.state,
            modal: {
                ...this.state.modal,
                [key]: false
            }
        })
    }

    onAddFormCancel = () => {
        this.cancelModal('add')
        this.addForm.resetFields()
        this.setState({
            edit: false,
            imgs: [],
            detailImgs: [],
        })
    }

    deleteEditImage = (index, name) => {
        const imgs = this.state.editValue[name]
        imgs.splice(index, 1)
        this.setState({
            editValue: {
                ...this.state.editValue,
                [name]: imgs,
            }
        })
    }

    uploadInputProps = (name) => {

        const fileList = this.state[name]

        return {

            onRemove: file => {
                this.setState(state => {
                    const index = state[name].indexOf(file);
                    const newFileList = state[name].slice();
                    newFileList.splice(index, 1);
                    return {
                        [name]: newFileList,
                    }
                })
            },

            beforeUpload: () => false,

            onChange: ({fileList,}) => {
                this.setState({
                    [name]: fileList,
                })
            },

            onPreview: async (file) => {
                if (!file.url && !file.preview) {
                    file.preview = await getBase64(file.originFileObj);
                }

                this.setState({
                    previewImage: file.url || file.preview,
                    previewTitle: file.name || file.url.substring(file.url.lastIndexOf('/') + 1),
                }, () => this.callModal('preview'));
            },

            fileList,
        }

    }


    render() {
        return (
            <>
                <Modal
                    visible={this.state.modal.preview}
                    title={this.state.previewTitle}
                    footer={null}
                    onCancel={() => this.cancelModal('preview')}
                >
                    <img alt="example" style={{ width: '100%' }} src={this.state.previewImage} />
                </Modal>
                <Modal
                    visible={this.state.modal.add}
                    onCancel={this.onAddFormCancel}
                    footer={null}
                    title={'茶叶表单'}
                    width='80%'
                >
                    <Form
                        {...formLayout}
                        name='add'
                        ref={el => this.addForm = el}
                        onFinish={this.onAdd}
                    >
                        {/*Id              int64 //修改的时候传，不修改传0*/}
                        {/*Pinpai          string //品牌*/}
                        <Form.Item
                            label="品牌"
                            name="Pinpai"
                        >
                            <Input placeholder='请输入品牌' />
                        </Form.Item>
                        {/*Name            string //名字*/}
                        <Form.Item
                            label="品名"
                            name="Name"
                        >
                            <Input placeholder='请输入品名'/>
                        </Form.Item>
                        {/*Price           int64  //价格*/}
                        <Form.Item
                            label="价格"
                            name="Price"
                        >
                            <InputNumber placeholder='请输入价格'/>
                        </Form.Item>
                        {/*Gongyi          string //工艺*/}
                        <Form.Item
                            label="工艺"
                            name="Gongyi"
                        >
                            <Input placeholder='请输入工艺'/>
                        </Form.Item>

                        {/*Style           string //类型*/}
                        <Form.Item
                            label="类型"
                            name="Style"
                        >
                            <Input placeholder='请输入类型'/>
                        </Form.Item>
                        {/*Guige           string //规格*/}
                        <Form.Item
                            label="规格"
                            name="Guige"
                        >
                            <Input placeholder='请输入规格'/>
                        </Form.Item>
                        {/*Pici            string //批次*/}
                        <Form.Item
                            label="批次"
                            name="Pici"
                        >
                            <Input placeholder='请输入批次'/>
                        </Form.Item>
                        {/*Weight          int64  //重量*/}
                        <Form.Item
                            label="重量"
                            name="Weight"
                        >
                            <InputNumber placeholder='请输入重量'/>
                        </Form.Item>
                        {/*Up              int    //涨幅*/}
                        <Form.Item
                            label="涨幅"
                            name="Up"
                        >
                            <InputNumber placeholder='请输入涨幅'/>
                        </Form.Item>
                        {/*Xulie           string //序列*/}
                        <Form.Item
                            label="序列"
                            name="Xulie"
                        >
                            <Input placeholder='请输入序列'/>
                        </Form.Item>
                        {/*Hot             int    //热度*/}
                        <Form.Item
                            label="热度"
                            name="Hot"
                        >
                            <InputNumber placeholder='请输入热度'/>
                        </Form.Item>
                        {/*Productiondate  int64  //生产日期*/}
                        {/*Expiredate      int64  //过期时间*/}

                        {/*Imgs            string //图片*/}
                        {this.state.edit && <Form.Item
                            label='轮播图图片'
                        >
                            {this.state.editValue.Imgs.map((src, index) => {
                                return <div
                                    key={index}
                                    style={{position: 'relative', display: 'inline-block'}}
                                >
                                    <img src={src} alt='' style={{width: 200}}/>
                                    <CloseCircleOutlined
                                        style={{position: 'absolute', top: 0, right: 0,}}
                                        onClick={() => {
                                            this.deleteEditImage(index, 'Imgs')
                                        }}
                                    />
                                </div>
                            })}
                        </Form.Item>}
                        <Form.Item
                            label="上传轮播图图片"
                        >
                            <Upload
                                listType="picture-card"
                                fileList={this.state.imgs}
                                {...this.uploadInputProps('imgs')}
                                multiple={true}
                            >
                                <Button icon={<UploadOutlined />}>上传轮播图</Button>
                            </Upload>
                        </Form.Item>
                        {/*Detailimgs      string//详情图片*/}
                        {this.state.edit && this.state.editValue.Detailimgs && <Form.Item
                            label='详情图片'
                        >
                            {this.state.editValue.Detailimgs.map((src, index) => {
                                return <div
                                    key={index}
                                    style={{position: 'relative', display: 'inline-block'}}
                                >
                                    <img src={src} alt='' style={{width: 200}}/>
                                    <CloseCircleOutlined
                                        style={{position: 'absolute', top: 0, right: 0,}}
                                        onClick={() => {
                                            this.deleteEditImage(index, 'Detailimgs')
                                        }}
                                    />
                                </div>
                            })}
                        </Form.Item>}
                        <Form.Item
                            label="上传详情图片"
                        >
                            <Upload
                                listType="picture-card"
                                fileList={this.state.imgs}
                                {...this.uploadInputProps('detailImgs')}
                                multiple={true}
                            >
                                <Button icon={<UploadOutlined />}>上传详情图片</Button>
                            </Upload>
                        </Form.Item>
                        <Form.Item {...formTailLayout}>

                            <Button type="primary" htmlType="submit">
                                提交
                            </Button>

                        </Form.Item>

                    </Form>
                </Modal>
                <Admin>
                    <div className='list-container'>
                        <div style={{marginBottom: '8px'}}>
                            {/*<Button onClick={*/}
                            {/*    () => this.callModal('add')}*/}
                            {/*>添加行情</Button>*/}

                        </div>
                        <Search
                            placeholder="请输入品牌名"
                            allowClear
                            enterButton="按品牌搜索"
                            size="large"
                            onSearch={this.onBrandSearch}
                            style={{
                                width: '500px',
                                marginBottom: '8px',
                                display: 'block'
                            }}
                        />
                        <Search
                            placeholder="请输入年份"
                            allowClear
                            enterButton="按年份搜索"
                            size="large"
                            onSearch={this.onYearSearch}
                            style={{
                                width: '500px',
                                marginBottom: '8px',
                                display: 'block'
                            }}
                        />
                        <Search
                            placeholder="请输入工艺"
                            allowClear
                            enterButton="按工艺搜索"
                            size="large"
                            onSearch={this.onTechnologySearch}
                            style={{
                                width: '500px',
                                marginBottom: '8px',
                                display: 'block'
                            }}
                        />
                        <Search
                            placeholder="请输入品名"
                            allowClear
                            enterButton="按品名搜索"
                            size="large"
                            onSearch={this.onNameSearch}
                            style={{
                                width: '500px',
                                marginBottom: '8px',
                                display: 'block'
                            }}
                        />
                        <Form
                            layout='inline'
                            style={{ marginBottom: 8 }}
                        >
                            <Form.Item label="热度降序">
                                <Switch checked={this.state.hot === 1} onChange={(value) => this.onSortChange(value, 'hot', 1)} />
                            </Form.Item>
                            <Form.Item label="热度升序">
                                <Switch checked={this.state.hot === 2} onChange={(value) => this.onSortChange(value, 'hot', 2)} />
                            </Form.Item>
                        </Form>
                        <Form
                            layout='inline'
                            style={{ marginBottom: 8 }}
                        >
                            <Form.Item label="价格降序">
                                <Switch checked={this.state.price === 1} onChange={(value) => this.onSortChange(value, 'price', 1)} />
                            </Form.Item>
                            <Form.Item label="价格升序">
                                <Switch checked={this.state.price === 2} onChange={(value) => this.onSortChange(value, 'price', 2)} />
                            </Form.Item>
                        </Form>
                        <Form
                            layout='inline'
                            style={{ marginBottom: 8 }}
                        >
                            <Form.Item label="涨幅降序">
                                <Switch checked={this.state.up === 1} onChange={(value) => this.onSortChange(value, 'up', 1)} />
                            </Form.Item>
                            <Form.Item label="涨幅降序">
                                <Switch checked={this.state.up === 2} onChange={(value) => this.onSortChange(value, 'up', 2)} />
                            </Form.Item>
                        </Form>
                        <Table
                            dataSource={this.state.list}
                            columns={this.columns}
                            pagination={false}
                            rowKey={(record, index) => index}
                        />
                        <PaginationFooter
                            pageIndex={this.state.p}
                            prevPage={this.prevPage}
                            nextPage={this.nextPage}
                        />
                    </div>
                </Admin>
            </>
        )
    }

}

export default Quotation